import Vue from 'vue'
import App from './App'
import store from './store'
import api from './api'
import util from './common/util.js'
import { baseUrl,brandId,brandName } from "./config";
import {MyStorageManage} from "./util/MyStorageManage.js"
Vue.config.productionTip = false
App.mpType = 'app'

Vue.prototype.$store = store
Vue.prototype.$api = api
Vue.prototype.$util = util
const msg = (title, duration = 1500, mask = false, icon = 'none') => {
	//统一提示方便全局修改
	if (Boolean(title) === false) {
		return;
	}
	uni.showToast({
		title,
		duration,
		mask,
		icon
	});
}

let userInfo = undefined

const logout = () => {
	userInfo = undefined
	uni.removeStorage({
		key: 'userInfo'
	})
}

const setUserInfo = (i) => {
	userInfo = i
}

const isVip = () => {
	return userInfo && userInfo.level
}

let loginLock = false
const connect =() =>{ //连接蓝牙设备
	var _this = this
	uni.createBLEConnection({
		deviceId: _this.deviceId,
		complete (e) {
			if (!e.errCode) {
				//获取蓝牙设备所有服务(service)。
				_this.getBLEDeviceServices()
			} else {
				uni.showToast({
					icon: 'none',
					title: '连接设备失败'
				})
			}
		}
	})
}
const request = (_gp, _mt, data = {}, failCallback) => {
	//异步请求数据
	return new Promise(resolve => {
		if (!userInfo || !userInfo.accessToken) {
			userInfo = uni.getStorageSync('userInfo')
		}
		let accessToken = userInfo ? userInfo.accessToken : ''
		let baseUrl = config.baseUrl
		uni.request({
			url: baseUrl + '/m.api',
			data: {
				...data,
				_gp,
				_mt
			},
			method: 'POST',
			header: {
				'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
				'ACCESSTOKEN': accessToken
			},
			success: (res) => {
				if (res.statusCode === 200) {
					if (res.data.errno === 200) {
						resolve(res.data);
					} else if (res.data.errno === 10001) {
						if (failCallback) {
							failCallback(res.data)
						}
						if (!loginLock) {
							loginLock = true
							uni.showModal({
								title: '登录提示',
								content: '您尚未登录，是否立即登录？',
								showCancel: true,
								confirmText: '登录',
								success: (e) => {
									if (e.confirm) {
										uni.navigateTo({
											url: '/pages/public/login'
										})
									}
								},
								fail: () => {},
								complete: () => {
									loginLock = false
								}
							})
						}

					} else {
						if (failCallback) {
							failCallback(res.data)
						} else {
							uni.showToast({
								title: res.data.errmsg,
								icon: 'none'
							})
						}
					}
				}
			}
		})
	})
}

const uploadImg = (successCallback) => {
	let baseUrl = config.baseUrl
	uni.chooseImage({
		sizeType: ['compressed'],
		success: function(res) {
			for (let i = 0; i < res.tempFilePaths.length; i++) {
				uni.request({
					url: baseUrl + '/upload',
					method: 'get',
					success: function(signRes) {
						uni.showLoading({
							title: '图片上传中',
						})
						let fileName = ('imgs/' + random_string(15) + get_suffix(res
							.tempFilePaths[i]))
						uni.uploadFile({
							url: signRes.data.baseUrl,
							filePath: res.tempFilePaths[i],
							name: 'file',
							formData: {
								name: res.tempFilePaths[i],
								key: fileName,
								policy: signRes.data.policy,
								OSSAccessKeyId: signRes.data.accessid,
								success_action_status: '200',
								signature: signRes.data.signature
							},
							success: function(uploadRes) {
								uni.hideLoading()
								if (uploadRes.statusCode === 200) {
									if (successCallback) {
										successCallback(signRes.data.baseUrl +
											fileName)
									} else {
										uni.showToast({
											title: '上传成功',
											icon: 'none'
										})
									}
								} else {
									uni.hideLoading()
									uni.showToast({
										title: '网络错误 code=' + uploadRes
											.statusCode,
										icon: 'none'
									})
								}
							}
						})
					}
				})
			}
		}
	})
}

function get_suffix(filename) {
	var pos = filename.lastIndexOf('.')
	var suffix = ''
	if (pos != -1) {
		suffix = filename.substring(pos)
	}
	return suffix;
}

function random_string(len) {
	len = len || 32;
	var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
	var maxPos = chars.length;
	var pwd = '';
	for (var i = 0; i < len; i++) {
		pwd += chars.charAt(Math.floor(Math.random() * maxPos));
	}
	return pwd;
}

const prePage = () => {
	let pages = getCurrentPages();
	let prePage = pages[pages.length - 2];
	// #ifdef H5
	return prePage;
	// #endif
	return prePage.$vm;
}

const globalData = {}

Vue.config.productionTip = false
Vue.prototype.$fire = new Vue();
Vue.prototype.$store = store;

function baseUrlFunc(url) {
	return `${baseUrl}${url}`;
}
/**
 * km 百米  10米
 * @param juli
 */
const jizhiConvert =  function (juli){
	if(juli==null||juli ===undefined){
		juli = -999
	}
	juli = juli/1000;
	if(juli<1){
		juli = juli*1000
		return juli.toFixed(0)+"米"
		this.$set(this.currentPos,"juli",)
	}else{
		return juli.toFixed(0)+"公里"
	}
}
const noOpen= function(){
	uni.showToast({
		title: "该功暂未开放，敬请期待",
		icon: 'none',
		duration: 2000
	});
	console.log("sss")
}
/**
 * 当前店铺是否打烊
 * @param item
 * @returns {boolean}
 */
const isOpenInRangeTime = function(item){
	console.log("fff",item)
	let {open_time="00:00:00",end_time="23:59:59"} = item;
	let currentTime = new Date();
	let year = currentTime.getFullYear();
	let month = currentTime.getMonth()+1;
	let day = currentTime.getDate();
	let beginTime = new Date(year+"/"+month+"/"+day+" "+open_time);
	let afterTime = new Date(year+"/"+month+"/"+day+" "+end_time);
	if(currentTime>=beginTime&&currentTime<=afterTime){
		return false;
	}
	return true;
}
const ajax = function(opt) {
	opt = opt || {};
	if (opt.url.indexOf('http') == -1) {
		opt.url = baseUrlFunc(opt.url) || '';
	}
	const accessToken =  uni.getStorageSync("accessToken");
	opt.data = opt.data || null;
	opt.method = opt.method || 'GET';
	opt.header = opt.header || {
		// 'Authorization': ComFunJS.token || '',
		'content-type': 'application/json',
		'Accept': 'application/json',
	};
	if (accessToken) {
		opt.header["ACCESSTOKEN"] = accessToken;
	}
	opt.success = opt.success || function() {};
	uni.request({
		url: opt.url,
		data: opt.data,
		method: opt.method,
		header: opt.header,
		dataType: 'json',
		success: function(res) {
			opt.success(res);
		},
		fail: function(res) {
			console.log(res)
			try{
				opt.fail ? opt.fail(res) : null
			}catch(e){
				//TODO handle the exception
			}
		},
		complete(res) {
			try{
				opt.complete ? opt.complete(res) : null
			}catch(e){
				//TODO handle the exception
			}
			if (res.data.status != 1000) {
				if (res.data.status === undefined) {
					// 请求错误
					// _this.logout();
					// // 回到登录页
					// uni.reLaunch({
					// 	url: '/pages/login/index'
					// });
					// return
				}
				if(res.data.status == 403){

				}
				uni.showToast({
					title: res.data.msg,
					icon: 'none',
					duration: 1000
				});
			}
		}
	})
}
const   getBrandInfo=  function (){
	return new Promise(resolve => {
		let flag =  customStoreageManage.getStorage("currentBrand")
		if(flag ==undefined||flag == null ||flag == '') {
			ajax({
				url: "/web/app-integral/get/" + brandId,
				method: "get",
				header: {
					"Content-Type": "application/x-www-form-urlencoded"
				},
				success: (res) => {
					const {data} = res.data || {};
					console.log("dddd", data)
					customStoreageManage.setStorage("currentBrand", data, 60)
					resolve(data)
				}
			});
		}else{
			resolve(flag)
		}
	})

}
let customStoreageManage = new MyStorageManage();
const getWxLocation = function () {
	// wx.showLoading({
	// 	title: '拼命加载中...',
	// 	mask: true,
	// })
	return new Promise((resolve, reject) => {
			resolve(customStoreageManage.getStorage("currentLocation"))
	})
}
const startWxLocation = function () {
	//#ifdef MP-ALIPAY
	return new Promise((resolve, reject) => {
		uni.getLocation({
			success: function (res) {
				customStoreageManage.setStorage("currentLocation", res)
				uni.hideLoading()
				console.log('当前位置的经度111：' + res.longitude);
				console.log('当前位置的纬度：' + res.latitude);
				resolve(res);

			}
		});
	})
	//#endif
    //#ifdef MP-WEIXIN
	return new Promise((resolve, reject) => {
		const _locationChangeFn = (res) => {
			customStoreageManage.setStorage("currentLocation", res)
			console.log('GET', customStoreageManage.getStorage("currentLocation"))
			uni.hideLoading()
			uni.offLocationChange(_locationChangeFn)
			resolve(res)
		}
		uni.startLocationUpdate({
			success: (res) => {
				customStoreageManage.setStorage("currentLocation", res)
				uni.onLocationChange(_locationChangeFn)
			},
			fail: (err) => {
				console.log('err', err)
				reject()
			}
		})
		// uni.getLocation({
		// 	success: function (res) {
		// 		resolve(res);
		// 		customStoreageManage.setStorage("currentLocation", res)
		// 		uni.hideLoading()
		// 		console.log('当前位置的经度111：' + res.longitude);
		// 		console.log('当前位置的纬度：' + res.latitude);
		// 	},
		// 	fail:(e) => {
		// 		console.log(e)
		// 	}
		// });
	})
	//#endif
}
const reloadMinShop =  async function reloadMinShop(){
	console.log("来了么？")
	uni.showLoading()
	let loca =  await getWxLocation()
	console.log("->" + JSON.stringify(loca))
	/**
	 * 获取最近一家店
	 */
	return new Promise(resolve => {
		ajax({
			url: "/web/map/qq/geo-coder-f",
			data: {
				location: loca.latitude + "," + loca.longitude,
			},
			method: "get",
			header: {
				"Content-Type": "application/x-www-form-urlencoded"
			},
			success: (res) => {
				// console.log(res);
				const {data} = res
				if (data.status === 0) {//说明请求成功
					resolve(data)
					// let {result} = data.data
					// let {ad_info, location} = result;
					// let {province, city, district} = ad_info
					// console.log("--->location",location)
					//
					// let {lat, lng} = location
					// //开始查当前城市最近的店
					// this.getMinShop(province, city, district, lat, lng);
					// return true;
				}


			}
		},error=>{
			error("失败")
		});

	})
}
const getMinShop = function (data){
	let {result} = data.data
	let {ad_info, location} = result;
	let {province, city, district} = ad_info
	console.log("--->location",location)

	let {lat, lng} = location
	let flag =  customStoreageManage.getStorage("currentcityShopsP")
	console.log("thisFlag",flag)
	return new Promise(resolve => {

		if(flag ==undefined||flag == null ||flag == ''){

			ajax({
				url: "/web/app-zzjg/zzjg-list",
				data: {
					lat: lat,
					lng: lng,
					sheng: province,
					shi: city,
					brandId: brandId
				},
				method: "get",
				header: {
					"Content-Type": "application/x-www-form-urlencoded"
				},
				success:(res)=> {
					// console.log(res);
					const { data } = res
					console.log("dddd",data)
					uni.setStorageSync("currentcityShops",data.data)
					customStoreageManage.setStorage("currentcityShopsP", data.data, 1)
					if(data.data.length<=0){ //说明当前城市没有店铺
						resolve(null)
					}else{
						resolve(data.data[0])
					}
					uni.hideLoading()

				}
			});
		}else{
			for(let jg of flag){
				customStoreageManage.setStorage("userSelect",jg,5)
				resolve(jg)
				break; //只取第一条也就是最近的一个店铺 然后跳出循环
			}
		}
	})

}
let baseComentApi = {
	msg,
	prePage,
	request,
	uploadImg,
	logout,
	isVip,
	setUserInfo,
	globalData,
	ajax,
	jizhiConvert,
	noOpen,
	customStoreageManage,
	getBrandInfo,
	brandId,
	brandName,
	getWxLocation,
	isOpenInRangeTime,
	reloadMinShop,
	getMinShop,
	startWxLocation

};
Object.assign(Vue.prototype.$api, baseComentApi)
Vue.prototype.$bus = new Vue()
Vue.prototype.commonData = {
	appId: "wx934bebd27a01e5f2",
	secret: "e4daa8fc2f5b2839aa606ce0c28b7d1d"
};
const app = new Vue({
	store,
	...App
})

app.$mount()
